CommonUtils.regNamespace("com.im.countStatic");
com.im.countStatic.invoke = function() {
	var param = {
		pageNumber: 1,
		pageSize: 20
	};
    var client = new com.im.common.ajax();
    var operType = "";
    var countStatic;

    function _init() {
        //加载列表信息
    	_initDataList();
    	//重置按钮
    	$('#ResetBtn').click(function (){
    		_resetSearchInfo();
    	});
        //查询按钮
        $("#SearchBtn").click(function(){
        	_loadDataList();
        });
        $('#detailModal').on('shown.bs.modal', function () {
            $("#detailList").empty();
            var param={
	  	      		pageInfo:{
	  	      			pageNumber: 1,
	  	          		pageSize: 20,
	  	      		},
	  	      		contractId:countStatic.contractId
	  	      	};
            _searchDetailList(param);
        });
      //所属规划-建设单位-实施项目
        $("#searchPlanProjClass").project2unit2itemCommpent({
            elmIdPlanTypeSel : "searchPlanProjClass",
            elmIdUnitSel : "searchOrgName",//组织单位下拉元素
            elmIdItemSel : "searchImpleProjName",//实施项目下拉元素
            orgType : "10",//初始化单位时，单位类型
            callbackFunc: function (callBackType, ret) {//下拉框值改变时回调
            	_loadDataList();
            }
        });
        //导出按钮
        $('#exportProjectPlanBtn').click(function (){
        	_exportList();
        });
    };
    //导出表格
    function _exportList(){
    	var param = {
    		    "classes": "com.im.service.metePay.smo.MetePayQuerySMOImpl",
    		    "fileName": "计量汇总列表",
    		    "method": "queryMetePayStaticList",
    		    "title": {
    		        "impleProjName":"实施项目名称",
    		        "contractCode":"合同编号",
    		        "contractName": "合同名称",
    		        "contractType": "合同类型",
    		        "contractTotal": "总金额",
    		        "contractClauseName": "支付条款",
    		        "contractItemName": "合同分项",
    		        "amonut": "数量",
    		        "itemTotal": "金额",
    		        "payment": "支付金额",
    		        "paymentRatio": "支付比例(%)",
    		        "declarer": "申请人",
    		        "declarerDt": "申请时间",
    		        "payCode": "支付编码",
    		        "liablePerson": "支付责任人",
    		        "payDt": "支付时间",
    		        "description": "备注"
    		    }
    		};
    	param.param={};
    	var impleProjName = $("#searchImpleProjName").val();
    	var contractCode = $("#searchContractCode").val();
    	var contractName = $("#searchContractName").val();
    	param.param.impleProjName = impleProjName;
        if(contractCode == ''){
        	delete param.param.contractCode;
        }else{
        	param.param.contractCode = contractCode;
        }
        param.param.contractName = contractName;
    	var url='/InfoManageWeb/commonService/export?json='+encodeURI(JSON.stringify(param));
    	window.open(url, '_blank');
    }
    //重置搜索条件
    function _resetSearchInfo(){
    	$('#searchOrgName').val("").trigger("change");
    	$('#searchPlanProjClass').val("").trigger("change");
    	$('#searchImpleProjName').val("").trigger("change");
    }
    //更新数据列表
    function _loadDataList(){
    	param.pageNumber = 1;
    	var impleProjId = $("#searchImpleProjName option:selected").attr("value");
    	var orgId = $("#searchOrgName option:selected").attr("value");
    	var planProjClass = $("#searchPlanProjClass option:selected").attr("value");
        param.impleProjId = impleProjId;
        param.orgId = orgId;
        param.planProjClass = planProjClass;
        $('#countStaticList').datagrid("load",param);
    }
    //明细
    function _detailList(index){
    	countStatic = $('#countStaticList').datagrid('getData').rows[index];
    	$('#detailImpleProjName').html(countStatic.impleProjName);
    	$('#detailContractName').html(countStatic.contractName);
    	$('#searchContractClauseName').html(countStatic.contractClauseName);
    	$('#detailModal').modal("show");
    }
    function _searchDetailList(param){
    	var columns=[[
		    {field:'contractItemName',width:100,title:"合同分项",rowspan:2,resizable:true},
		    {field:'amonut',title:"数量",width:80,rowspan:2,resizable:true},
		    {field:'unitPrice',title:"单价",width:80,rowspan:2,resizable:true},
		    {field:'otherCharge',title:"其它费用",width:80,rowspan:2,resizable:true},
		    {field:'itemTotal',title:"分项总额",width:80,rowspan:2,resizable:true}
		],[]];
    	var result = client.callAsJson("metePayService/queryMetePayStaticDetailList", param);
    	var num = 0;
    	$.each(result.result.rows,function (index,item){
    		if((item.metePayList).length > num){
    			num = (item.metePayList).length;
    		}
    	});
    	for(var i =0;i<num;i++){
    		columns[0].push({field:'pay',title:"第"+(i+1)+"次支付",width:100,colspan:3,resizable:true});
    		var payment = {
    			field:'payment'+i,
    			title:"支付金额",
    			width:80,
    			resizable:true,
        		formatter: function(value,row,index){
        			var nowNum = Number((this.field).substring((this.field).length-1,(this.field).length));
        			if((row.metePayList)[nowNum]){
        				return (row.metePayList)[nowNum].payment;
        			}else{
        				return '';
        			}
        	    }
    		};
    		var payRatio = {
        			field:'payRatio'+i,
        			title:"支付比例",
        			width:80,
        			resizable:true,
            		formatter: function(value,row,index){
            			var nowNum = Number((this.field).substring((this.field).length-1,(this.field).length));
            			if((row.metePayList)[nowNum]){
            				return (row.metePayList)[nowNum].payRatio;
            			}else{
            				return '';
            			}
            	    }
        		};
    		var payDt = {
        			field:'payDt'+i,
        			title:"申请时间",
        			width:80,
        			resizable:true,
            		formatter: function(value,row,index){
            			var nowNum = Number((this.field).substring((this.field).length-1,(this.field).length));
            			if((row.metePayList)[nowNum]){
            				return (row.metePayList)[nowNum].payDt;
            			}else{
            				return '';
            			}
            	    }
        		};
    		columns[1].push(payment);
    		columns[1].push(payRatio);
    		columns[1].push(payDt);
    	}
    	$('#detailList').datagrid({
    	    method:'post',
    	    dataType : 'json',
    	    queryParams:param,
    	    pagination:true,
    	    nowrap:false,
    	    fitColumns:true,
    	    columns:columns,
    	    loadMsg:'数据加载中，请耐心等待',
    	    data:result.result
    	});
    	var p = $('#detailList').datagrid('getPager');
	  	  $(p).pagination({
	  	    pageSize: 20,
	  	    pageList: [10,20,30],
	  	    beforePageText: '第',
	  	    afterPageText: '页    共 {pages}  页',
	  	    displayMsg: '当前显示 {from} - {to} 条记录 共 {total}  条记录',
	  	    onSelectPage:function(pageNumber, pageSize){
	  	    	var param={
	  	      		pageInfo:{
	  	      			pageNumber: pageNumber,
	  	          		pageSize: pageSize,
	  	      		},
	  	      		contractId:countStatic.contractId
	  	      	};
	  	    	_searchDetailList(param);
	  	    }
	  	  });
    }
  //合并单元格
    function mergeCellsByField(tableID, fldList,other) {
    	var Arr = fldList.split(",");  
        var dg = $('#' + tableID);  
        var fldName;  
        var RowCount = dg.datagrid("getRows").length;  
        var span;  
        var PerValue = "";  
        var CurValue = "";  
        var length = Arr.length - 1;  
        for (i = length; i >= 0; i--) {  
            fldName = Arr[i];  
            PerValue = "";  
            span = 1;  
            for (row = 0; row <= RowCount; row++) {  
                if (row == RowCount) {  
                    CurValue = "";  
                }  
                else {  
                    CurValue = dg.datagrid("getRows")[row][fldName];  
                } 
                if (PerValue === CurValue) {  
                    span += 1;  
                }  
                else {  
                    var index = row - span;  
                    dg.datagrid('mergeCells', {  
                        index: index,  
                        field: fldName,  
                        rowspan: span,  
                        colspan: null  
                    });  
                    var name = other.split(","); 
                    $.each(name,function (i,item){
                    	dg.datagrid('mergeCells', {  
                            index: index,  
                            field: item,  
                            rowspan: span,  
                            colspan: null  
                        });
                    });
                    span = 1;  
                    PerValue = CurValue;  
                }  
            }  
        }  
    }
    //初始化表格数据
    function _initDataList(){
    	var columns=[[
    		{field:'index',title:"序号",width:40,resizable:true,
              	formatter: function(value,row,index){
                      return  index+1;
                  }
		    },
		    {field:'impleProjName',width:150,title:"实施项目名称",resizable:true},
		    {field:'contractName',width:100,title:"合同名称",resizable:true},
		    {field:'contractTotal',width:100,title:"总金额（万元）",resizable:true},
		    {field:'contractClauseName',width:100,title:"支付条款",resizable:true},
		    {field:'contractItemName',width:100,title:"合同分项",resizable:true},
		    {field:'amonut',title:"数量",width:60,resizable:true},
		    {field:'unitPrice',title:"单价（万元）",width:100,resizable:true},
		    {field:'otherCharge',title:"其它费用（万元）",width:120,resizable:true},
		    {field:'itemTotal',title:"分项总额（万元）",width:120,resizable:true},
		    {field:'paymentRatio',title:"支付比例(%)",width:100,resizable:true, formatter: function(value,row,index){
                if(value==null){
	            	return  "";
	            }else{
	            	return  value+'%';
	            }
	    }},
		    {field:'payment',title:"支付金额（万元）",width:120,resizable:true},
    	    {field:'operation',title:"操作",width:60,align:'center',resizable:true,
    	        formatter: function(value,row,index){
    	            return  '<a href="javascript:; "onclick="com.im.countStatic.invoke.detailList(\''+index+'\')" >明细</a> ';
    	    }}
//		    {field:'declarer',title:"申请人",resizable:true},
//		    {field:'declarerDt',title:"申请时间",resizable:true},
//		    {field:'payCode',title:"支付编码",resizable:true},
//		    {field:'liablePerson',title:"支付责任人",resizable:true},
//		    {field:'payDt',title:"支付时间",resizable:true},
//		    {field:'description',title:"备注",resizable:true}
		]];
    	$('#countStaticList').datagrid({
    	    url:'/InfoManageWeb/metePayService/queryMetePayStaticList',
    	    method:'post',
    	    dataType : 'json',
    	    queryParams:param,
    	    pagination:true,
    	    nowrap:false,
    	    fitColumns:true,
    	    columns:columns,
    	    loadMsg:'数据加载中，请耐心等待',
    	    onBeforeLoad : function(param){
	    	    for (var key in param) {
		    	    if(key=="rows"){
		    	    	delete param[key];
		    	    }
		    	}
    	    },
    	    loadFilter:function(data){
    	      if(data.resultCode!=0){
    	        toastr.error(data.resultCode);
    	        return null;
    	      }else{
    	        return data.result;
    	      }
    	    },
    	    onLoadSuccess: function (data) {
                if (data.rows.length > 0) {
                	mergeCellsByField('countStaticList','contractName',"impleProjName,contractTotal,contractClauseName,operation");
                }
            }
    	});
    	var p = $('#countStaticList').datagrid('getPager');
    	  $(p).pagination({
    	    pageSize: 20,
    	    pageList: [10,20,30],
    	    beforePageText: '第',
    	    afterPageText: '页    共 {pages}  页',
    	    displayMsg: '当前显示 {from} - {to} 条记录 共 {total}  条记录',
    	    onSelectPage:function(pageNumber, pageSize){
    	      param.pageNumber=pageNumber;
    	      param.pageSize=pageSize;
    	        var impleProjId = $("#searchImpleProjName option:selected").attr("value");
    	    	var orgId = $("#searchOrgName option:selected").attr("value");
    	    	var planProjClass = $("#searchPlanProjClass option:selected").attr("value");
    	        param.impleProjId = impleProjId;
    	        param.orgId = orgId;
    	        param.planProjClass = planProjClass;
    	      $('#countStaticList').datagrid('reload',param);
    	    }
    	  });
    }
	return {
		init : _init,
		detailList: _detailList
	}
}();

$(function() {
	com.im.countStatic.invoke.init();
});